package com.discuss.community.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.core.ApplicationMapping;
import org.apache.commons.lang3.CharUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SensitiveFilter {

    // 替换符
    private static final String REPLACEMENT = "***";

    // 根节点
    private TrieNode root = new TrieNode();

    // 当构造方法被调后，立即执行该方法
    @PostConstruct
    public void init() {
        try(
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is))
        ) {
            String keyword = null;
            while((keyword = reader.readLine()) != null) {
                this.addKeyWord(keyword);
            }
        }catch (IOException e) {
            log.error("加载敏感文件失败" + e.getMessage());
        }

    }

    /**
     * 过滤敏感次=词
     * @param text 待过滤的文本
     * @return 过滤后的文本
     */
    public String filter(String text) {
        if(StringUtils.isEmpty(text)) {
            return null;
        }
        // 指向树的指针
        TrieNode node = root;
        // 文本的快指针
        int begin = 0;
        // 文本的慢指针
        int position = 0;
        // 结果文本
        StringBuilder result = new StringBuilder();
        final int n = text.length();
        while (position < n) {
            Character c = text.charAt(position);

            // 跳过符号
            if(isSymbol(c)) {
                if(node == root) {
                    result.append(c);
                    begin++;
                }
                position++;
                continue;
            }
            node = node.getSubNodeByChar(c);

            if(node == null) {
                // 以Begin开头的字符不是敏感词
                result.append(text.charAt(begin));
                // 进入下一个位置
                position = ++begin;
                node = root;
            }else if(node.isKeyWordsEnd()) {
                // 发现敏感词
                result.append(REPLACEMENT);
                // 进入下一个位置
                begin = ++ position;
                node = root;
            }else {
                position++;
            }
        }

        // 将最后一批字符计入结果
        result.append(text.substring(begin));

        return result.toString();

    }

    private boolean isSymbol(Character c) {
        // c < 0x2E80 || c > 0x9FFF 东亚文字范围
        return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
    }


    // 将一个敏感词添加到前缀树中
    private void addKeyWord(String keyword) {
        int n = keyword.length();
        TrieNode temp = root;
        for(int i = 0; i < n; i++) {
            final char c = keyword.charAt(i);
            TrieNode subNode = temp.subNode.get(c);

            if(subNode == null) {
                subNode = new TrieNode();
                temp.addSubNode(c, subNode);
            }

            temp = subNode;

            // 设置结束标记
            if(i == n - 1) {
                temp.setKeyWordsEnd(true);
            }

        }
    }

    // 前缀树
    private class TrieNode {
        // 关键词结束标记
        private boolean isKeyWordsEnd = false;
        // 子节点
        private Map<Character,TrieNode> subNode = new HashMap<>();

        public boolean isKeyWordsEnd() {
            return isKeyWordsEnd;
        }

        public void  setKeyWordsEnd(boolean keyWordsEnd) {
            isKeyWordsEnd = keyWordsEnd;
        }

        // 添加子节点
        public void addSubNode(Character c, TrieNode node) {
            subNode.put(c,node);
        }

        // 获取子节点
        public TrieNode getSubNodeByChar(Character c) {
            return subNode.get(c);
        }


    }


}
